package cn.com.manager.dao.weibo;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.DefaultSortParameters;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

public class RedisBase {
	@Autowired
	public StringRedisTemplate stringRedisTemplate;
/*	@Autowired
	public RedisTemplate<String, Object> redisTemplate;*/

	/**
	 * 判断某个键是否存在
	 * 
	 * @param key
	 * @return
	 */
	public boolean keyExists(String key) {
		return stringRedisTemplate.execute(new RedisCallback<Boolean>() {

			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				Boolean exists = connection.exists(stringRedisTemplate.getStringSerializer().serialize(key));
				return exists;
			}

		});
	}

	/**
	 * 获取链表中内容数量
	 * 
	 * @param key
	 * @return
	 */
	public Long keyLen(String key) {
		return stringRedisTemplate.execute(new RedisCallback<Long>() {

			@Override
			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.lLen(stringRedisTemplate.getStringSerializer().serialize(key));
			}
		});
	}

	/**
	 * 获取有序集合长度
	 * @param key
	 * @return
	 */
	public Long ZSetLen(String key) {
		return stringRedisTemplate.execute(new RedisCallback<Long>() {

			@Override
			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				return connection.zCard(stringRedisTemplate.getStringSerializer().serialize(key));
			}

		});
	}

	/**
	 * 获取主键
	 * 
	 * @param key
	 * @return
	 */
	public Long getPrimaryKey(String key) {
		boolean keyExists = keyExists(key);
		if (!keyExists) {
			stringRedisTemplate.opsForValue().set(key, "1");
		}
		return stringRedisTemplate.opsForValue().increment(key, 1);
	}

	/**
	 * hash增加
	 * 
	 * @param key
	 * @param value
	 */
	public void hashAdd(String key, Map<String, Object> value) {
		stringRedisTemplate.opsForHash().putAll(key, value);
	}
}
